/*
 * @Date: 2024-06-23 17:49:08
 */
const Front = require('./Front.js');
const fs = require('fs');
const path = require('path');
const request = require('sync-request');
const { exit } = require('process');

module.exports = class extends Front {
    font_path = "log/";
    log_path = '';
    saveTime;
    push_config;
    constructor(push_config, log) {
        super();
        this.push_config = push_config;
        this.saveTime = log.saveTime;
        if (!fs.existsSync(this.font_path)) fs.mkdirSync(this.font_path);
        this.font_path = this.font_path + this.getday() + "/";
        if (!fs.existsSync(this.font_path)) fs.mkdirSync(this.font_path);
        this.log_path = this.font_path + this.gettime() + '.log';
        const paths = fs.readdirSync("log/");
        for (let i = 0; i < paths.length; i++) {
            let path = paths[i].replace(/_/g, "-");
            let now_time = new Date(this.getday().replace(/_/g, "-")).getTime();
            let path_time = new Date(path).getTime();
            if (now_time - path_time > this.saveTime * 24 * 60 * 60 * 1000) {
                console.log("删除过期日志：" + paths[i]);
                deleteFolderAndContents("log/" + paths[i])
            }

        }
        fs.writeFileSync(this.log_path, '');
    }

    failure(msg) {
        console.error(msg);
        fs.appendFileSync(this.log_path, this.getFormattedTime() + ' [failure] ' + msg + '\n');
        this.pushMeNotify('[f]3G阳光牧场', msg, {
            date: this.getFormattedTime(),
            type: "text"
        });
    }
    warning(msg) {
        console.warn(msg);
        fs.appendFileSync(this.log_path, this.getFormattedTime() + ' [warning] ' + msg + '\n');
        this.pushMeNotify('[w]3G阳光牧场', msg, {
            date: this.getFormattedTime(),
            type: "text"
        });
    }
    success(msg) {
        console.log(msg);
        fs.appendFileSync(this.log_path, this.getFormattedTime() + ' [success] ' + msg + '\n');
        this.pushMeNotify('[s]3G阳光牧场', msg, {
            date: this.getFormattedTime(),
            type: "text"
        });
    }
    info(msg) {
        console.info(msg);
        fs.appendFileSync(this.log_path, this.getFormattedTime() + ' [info] ' + msg + '\n');
        this.pushMeNotify('[i]3G阳光牧场', msg, {
            date: this.getFormattedTime(),
            type: "text"
        });
    }
    log(msg) {
        console.log(msg);
        fs.appendFileSync(this.log_path, this.getFormattedTime() + ' [log] ' + msg + '\n');
    }
    getFormattedTime() {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const milliseconds = String(date.getMilliseconds()).padStart(3, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    }

    getday() {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}_${month}_${day}`;
    }

    gettime() {
        const date = new Date();
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${hours}_${minutes}`;
    }

    pushMeNotify(text, desp, params = {}) {
        return new Promise((resolve) => {
            const { PUSHME_KEY, PUSHME_URL } = this.push_config;
            if (PUSHME_KEY) {
                const options = {
                    url: PUSHME_URL || 'https://push.i-i.me',
                    json: { push_key: PUSHME_KEY, title: text, content: desp, ...params },
                    headers: {
                        'Content-Type': 'application/json',
                    },
                };
                request('POST', options.url, {
                    'headers': options.headers,
                    'body': JSON.stringify(options.json, true)
                });
            } else {
                resolve();
            }
        });
    }
}

function deleteFolderAndContents(folderPath) {
    let files = fs.readdirSync(folderPath);

    for (let file of files) {
      let curPath = path.join(folderPath, file);
      let stats = fs.statSync(curPath);
  
      if (stats.isFile()) {
        fs.unlinkSync(curPath);
      } else if (stats.isDirectory()) {
        deleteFolderAndContentsSync(curPath);
      }
    }
  
    fs.rmdirSync(folderPath);
  }